package com.yangle.shell.service.impl;

import com.yangle.shell.bean.OrderDetail;
import com.yangle.shell.bean.OrderMaster;
import com.yangle.shell.bean.ProductInfo;
import com.yangle.shell.dao.OrderDetailRepository;
import com.yangle.shell.dao.OrderMasterRepository;
import com.yangle.shell.dao.ProductInfoRepository;
import com.yangle.shell.dto.CartDto;
import com.yangle.shell.dto.OrderMasterDto;
import com.yangle.shell.enums.ExceptionTypeEnum;
import com.yangle.shell.exception.SellException;
import com.yangle.shell.service.OrderService;
import com.yangle.shell.service.ProductInfoService;
import com.yangle.shell.util.GenUniqueId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Author: yangle
 * Create Data: 2020/12/5
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ProductInfoRepository productInfoRepository;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private OrderMasterRepository orderMasterRepository;
    @Autowired
    ProductInfoService productInfoService;

    @Override
    @Transactional
    public OrderMasterDto createOrder(OrderMasterDto orderMasterDto) {
        /**
         * name: "张三"
         * phone: "18868822111"
         * address: "慕课网总部"
         * openid: "ew3euwhd7sjw9diwkq" //用户的微信openid
         * items: [{
         *     productId: "1423113435324",
         *     productQuantity: 2 //购买数量
         * }]
         * 参数为页面参数
         * 1.接收参数转化为DTO对象
         * 2.通过list对象Items获取商品id->productId
         * 3.通过商品id查询商品信息，计算订单总价，通过商品信息生成订单详情表（orderDetail）
         * ，需要全局生成订单详情Id（detailId）
         * 4.生成订单表（orderMaster）数据,将DTO的属性copy到订单表，需要全局生成订单Id（orderId）
         * 5.通过购买数量减少库存
         *345都需要进行数据库操作（将数据写入数据库）
         * */
        //全局生成订单id
        String orderId = GenUniqueId.getId();
        //定义总价
        BigDecimal total = new BigDecimal(0);

        for (OrderDetail orderDetail:orderMasterDto.getOrderDetailList()){
            //获取商品信息
            ProductInfo productInfo = productInfoRepository.getOne(orderDetail.getProductId());
            if(productInfo==null){
                throw new SellException(ExceptionTypeEnum.PRODUCT_NOT_EXIST.getMessage());
            }
            //计算总价
             total = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity())).add(total);
            //将订单详情对象插入数据库
            BeanUtils.copyProperties(productInfo,orderDetail);
            //生成订单详情id
            orderDetail.setDetailId(GenUniqueId.getId());
            orderDetail.setOrderId(orderId);
            orderDetailRepository.save(orderDetail);
        }
        //生成订单对象，将DTO的属性copy到订单对象并插入数据库
        //需要先进行属性copy，否则设置的订单id属性将会被null值覆盖
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderMasterDto,orderMaster);
        orderMaster.setOrderId(orderId);
        orderMaster.setOrderAmount(total);
        orderMasterRepository.save(orderMaster);
        //减少库存（通过页面的两个参数productId: "1423113435324",
        //             productQuantity: 2）
        //来进行操作，需要一个存放这两个字段的DTO
        List<CartDto> cartDtoList = new ArrayList<>();
        cartDtoList=orderMasterDto.getOrderDetailList().stream()
                .map(e -> new CartDto(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.decreaseStock(cartDtoList);
        return orderMasterDto;
    }

    @Override
    public OrderMasterDto findOrderById(String orderId) {
        return null;
    }

    @Override
    public Page<OrderMasterDto> findList(String openId, Pageable pageable) {
        return null;
    }

    @Override
    public OrderMasterDto cancelOrder(OrderMasterDto orderMasterDto) {
        return null;
    }

    @Override
    public OrderMasterDto finishOrder(OrderMasterDto orderMasterDto) {
        return null;
    }

    @Override
    public OrderMasterDto payOrder(OrderMasterDto orderMasterDto) {
        return null;
    }
}
